package ar.edu.sccs.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;

import ar.edu.sccs.entities.User;
import ar.edu.sccs.monitoring.logging.SCCSLogger;
import ar.edu.sccs.util.Constants;
import ar.edu.sccs.util.XmlHelper;

public class XmlModule {

	static Logger logger = SCCSLogger.getLogger(XmlModule.class);

	private Map<String, String> userConfig;

	public XmlModule() {
		userConfig = new HashMap<String, String>();
	}

	public User addUser(User user) {
		logger.info("XmlModule.addUser: " + user.toString());

		userConfig.put(user.getId(), user.getPassword());
		return user;
	}

	public User delUser(User user) {
		logger.info("XmlModule.delUser: " + user.toString());

		userConfig.remove(user.getId());
		return user;
	}

	public User alterUser(User user) {
		logger.info("XmlModule.alterUser: " + user.toString());

		userConfig.remove(user.getId());
		userConfig.put(user.getId(), user.getPassword());
		return user;
	}

	public List<User> findUserById(User user) {
		logger.info("XmlModule.findUserById: " + user.toString());

		userConfig.get(user.getId());
		List<User> listUser = new ArrayList<User>();
		listUser.add(user);
		return listUser;
	}

	public List<User> findAllUsers() {
		logger.info("XmlModule.findAllUsers");

		List<User> listUser = new ArrayList<User>();
		for (Iterator<String> keys = userConfig.keySet().iterator(); keys.hasNext();) {
			String key = keys.next();
			listUser.add(new User(key, null, userConfig.get(key)));
		}
		return listUser;
	}

	public boolean validateUser(User user) {
		logger.info("XmlModule.validateUser: " + user.toString());

		return user.getName().equals(user.getPassword());
//		return userConfig.containsKey(user.getId());
	}

	private void setXmlString(String xmlString) {
		if (xmlString == null)
			return;

		Document document = XmlHelper.parse(xmlString);
		for (Element e : (List<Element>) document.selectNodes(Constants.Xml.USER_XPATH)) {
			String key = e.attributeValue(Constants.Xml.USER_ID);
			String value = e.attributeValue(Constants.Xml.USER_PWD);
			userConfig.put(key, value);
		}
	}

	private String getXmlString() {
		Document d = XmlHelper.getNewDocument(Constants.Xml.METADATA);
		Element root = d.getRootElement();
		Element user = root.addElement(Constants.Xml.CONFIG);
		for (Map.Entry<String, String> entry : userConfig.entrySet()) {
			Element e = user.addElement(Constants.Xml.USER);
			e.addAttribute(Constants.Xml.USER_ID, entry.getKey());
			e.addAttribute(Constants.Xml.USER_PWD, entry.getValue());
		}
		return d.asXML();
	}

	public String getPrettyXml() {
		return XmlHelper.getAsPrettyXml(getXmlString());
	}
}
